package com.sinosoft.moniter.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class SFTP {
	static ChannelSftp sftp = null;
	static JSch jsch = new JSch();
	static Session sshSession = null;

	/**
	 * 连接sftp服务器
	 * 
	 * @param host
	 *            主机
	 * @param port
	 *            端口
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return
	 */
	public static ChannelSftp connect(String host, int port, String username,
			String password) {
		if (sftp != null && sftp.isConnected() && !sftp.isClosed()) {
//			System.out.println("sftp 已经初始。");
		} else {
			try {
				jsch.getSession(username, host, port);
				sshSession = jsch.getSession(username, host, port);
//				System.out.println("Session created.");
				sshSession.setPassword(password);
				Properties sshConfig = new Properties();
				sshConfig.put("StrictHostKeyChecking", "no");
				sshSession.setConfig(sshConfig);
				sshSession.connect();
//				System.out.println("Session connected.");
				Channel channel = sshSession.openChannel("sftp");
				channel.connect();
				sftp = (ChannelSftp) channel;
				System.out.println("Connected to " + host + ".");
			} catch (Exception e) {
				System.err.println("连接" + host + "服务器出现问题。\n" + e.getMessage());
				disconnect();
			}
		}
		return sftp;
	}

	/**
	 * 断开连接
	 */
	public static void disconnect() {
		if (sshSession != null && sshSession.isConnected()) {
			sshSession.disconnect();
		}
		if (sftp != null && sftp.isConnected()) {
			sftp.disconnect();
		}
	}

	/**
	 * 上传文件
	 * 
	 * @param directory
	 *            上传的目录
	 * @param uploadFile
	 *            要上传的文件
	 * @param sftp
	 */
	public void upload(String directory, String uploadFile, ChannelSftp sftp) {
		try {
			sftp.cd(directory);
			File file = new File(uploadFile);
			System.out.println("文件【" + file.getName() + "】正在上传，请稍后。");
			Date date1 = new Date();
			sftp.put(new FileInputStream(file), file.getName());
			Date date2 = new Date();
			System.out.println("文件上传成功。\n使用时间为：【"
					+ (date2.getTime() - date1.getTime()) + "】毫秒。");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 下载文件
	 * 
	 * @param directory
	 *            下载目录
	 * @param downloadFile
	 *            下载的文件名称 不包含路径
	 * @param saveFile
	 *            存在本地的路径及名称
	 * @param sftp
	 */
	public void download(String directory, String downloadFile,
			String saveFile, ChannelSftp sftp) {
		try {
			sftp.cd(directory);
			File file = new File(saveFile);
			System.out.println("文件【" + file.getName() + "】正在下载，请稍后。");
			Date date1 = new Date();
			sftp.get(downloadFile, new FileOutputStream(file));
			Date date2 = new Date();
			System.out.println("文件下载成功。\n使用时间为：【"
					+ (date2.getTime() - date1.getTime()) + "】毫秒。");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param directory
	 *            要删除文件所在目录
	 * @param deleteFile
	 *            要删除的文件
	 * @param sftp
	 */
	public void delete(String directory, String deleteFile, ChannelSftp sftp) {
		try {
			sftp.cd(directory);
			sftp.rm(deleteFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 列出目录下的文件
	 * 
	 * @param directory
	 *            要列出的目录
	 * @param sftp
	 * @return
	 * @throws SftpException
	 */
	public Vector listFiles(String directory, ChannelSftp sftp)
			throws SftpException {
		return sftp.ls(directory);
	}

	public static void main(String[] args) throws SftpException {
		/*SFTP sf = new SFTP();
		String host = "172.20.241.80";
		int port = 22;
		String username = "gscx000108";
		String password = "A7YPd2";
		String directory = "/data/000108/bddj/upload_16818_test/";
		ChannelSftp sftp = sf.connect(host, port, username, password);
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		String fileName = format.format(date);

		System.out.println(sf.checkPath(directory,
				"H_000112PHIS0000000009_019.zip", sftp));*/

		/*
		 * boolean flag=sf.checkPath(directory,fileName,sftp); if(flag){
		 * System.out.println("文件路径已存在。"); }else{
		 * System.out.println("文件路径不存在，开始创建。"); sftp.cd(directory);
		 * sftp.mkdir(fileName); System.out.println("创建完毕。"); }
		 */
		// sf.upload("/data/000108/bddj/upload_16818_test",
		// "D:\\000112PHIS0000000009\\H_000112PHIS0000000009_019.zip", sftp);
		/*sf.download(directory, "H_000112PHIS0000000009_019.zip",
				"D:\\000112PHIS0000000009\\", sftp);
		sftp.disconnect();
		sftp.exit();*/
	}

	public boolean checkPath(String directory, String fileName, ChannelSftp sftp)
			throws SftpException {
		Vector<?> vector = sftp.ls(directory);
		boolean flag = false;
		for (Object item : vector) {
			LsEntry entry = (LsEntry) item;
			if (fileName.equals(entry.getFilename())) {
				flag = true;
				break;
			}
		}
		return flag;
	}

}